package com.example.venue_reservation_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.venue_reservation_service.domain.Question;
import com.example.venue_reservation_service.domain.Reply;
import com.example.venue_reservation_service.dto.ReplyDTO;
import com.example.venue_reservation_service.mapper.QuestionMapper;
import com.example.venue_reservation_service.mapper.UserMapper;
import com.example.venue_reservation_service.service.ReplyService;
import com.example.venue_reservation_service.mapper.ReplyMapper;
import com.example.venue_reservation_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
* @author 31586
* @description 针对表【venue_reply(回复记录表)】的数据库操作Service实现
* @createDate 2025-06-21 14:15:36
*/
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply>
    implements ReplyService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Override
    public Result createReply(ReplyDTO dto) {
        String content = dto.getContent().trim();
        if (StrUtil.isBlank(content)) {
            return Result.fail("回复内容不能为空");
        }
        Reply reply = getOne(Wrappers.<Reply>lambdaQuery()
                .eq(Reply::getAdminId, dto.getAdminId())
                .eq(Reply::getQuestionId, dto.getQuestionId()));
        if (Optional.ofNullable(reply).isEmpty()) {
            reply = BeanUtil.copyProperties(dto, Reply.class);
            reply.setCreatedTime(LocalDateTime.now());
        }else{
            reply.setContent(dto.getContent());
        }
        reply.setUpdatedTime(LocalDateTime.now());
        saveOrUpdate(reply);
        Question question = questionMapper.selectById(reply.getQuestionId());
        if (Optional.ofNullable(question).isPresent() && question.getStatus() == 0) {
            question.setStatus(1);
            questionMapper.updateById(question);
        }
        return Result.ok(reply).message("回复成功");
    }

    @Override
    public Result viewReply(Integer id) {
        Question question = questionMapper.selectById(id);
        if (Optional.ofNullable(question).isEmpty()) {
            return Result.fail().message("问题信息不存在");
        }
        if (question.getStatus() == 0) {
            return Result.ok().message("该问题未被回复");
        }
        return Result.ok(getOne(Wrappers.<Reply>lambdaQuery().eq(Reply::getQuestionId, id))).message("加载成功");
    }
}




